﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace IslandInterloper.Engine
{
    internal abstract class GameClientCollection<KeyType,ValueType> : GameClient where ValueType : GameClient
    {
        protected Dictionary<KeyType, ValueType> collection = new Dictionary<KeyType, ValueType>();
        public Dictionary<KeyType, ValueType>.KeyCollection Keys
        {
            get
            {
                return collection.Keys;
            }
        }
        public ValueType this[KeyType key]
        {
            get
            {
                if (collection.ContainsKey(key))
                {
                    return collection[key];
                }
                else
                {
                    return default(ValueType);
                }
            }
        }
        internal GameClientCollection(Game theGame)
            : base(theGame)
        {
        }
        internal GameClientCollection(Game theGame, XElement element)
            : base(theGame)
        {
            FromXElement(element);
        }
        protected abstract ValueType LoadItemFromXElement(XElement element);
        protected abstract KeyType LoadKeyFromXElement(XElement element);
        protected abstract XName KeyToXName(KeyType theKey);
        private void FromXElement(XElement element)
        {
            collection.Clear();
            foreach (XElement subElement in element.Elements())
            {
                collection.Add(LoadKeyFromXElement(subElement), LoadItemFromXElement(subElement));
            }
        }
        public override XElement ToXElement(XName xName)
        {
            XElement result = new XElement(xName);
            foreach (KeyType key in Keys)
            {
                result.Add(collection[key].ToXElement(KeyToXName(key)));
            }
            return result;
        }
    }
}
